import makeActionCreator from 'utils/makeActionCreator'
import fetch from 'isomorphic-fetch'

import {
  RECEIVE_FILM_DETAIL,
  INPUT_SHORT_COMMENT,
  INSERT_SHORT_COMMENT,
  ESCAPE_FILM_DETAIL
} from './consts'

export const receiveFilmDetail =
  makeActionCreator(RECEIVE_FILM_DETAIL, 'data')
export const shortCommentChange =
  makeActionCreator(INPUT_SHORT_COMMENT, 'text')
export const insertComment =
  makeActionCreator(INSERT_SHORT_COMMENT, 'id', 'time', 'content')
export const escape =
  makeActionCreator(ESCAPE_FILM_DETAIL)

export const fetchFilmDetail = function(filmID){
  return function(dispatch){
    const url = '/films/' + filmID
    const options = {
      method: 'GET'
    }
    fetch(url, options).then(res => {
      if(res.ok){
        res.json().then(data => {
          dispatch(receiveFilmDetail(data))
        })
      }
    })
  }
}

export const submitComment = () => (dispatch, getState) => {
  const time = new Date().toLocaleString()
  const content = getState().filmDetail.writingComment.text
  const filmID = getState().filmDetail.info.id
  const body = `time=${time}&content=${content}&filmID=${filmID}`
  fetch('/comments', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body
  }).then(
    res => res.json().then(
      ({id, time, content}) => dispatch(insertComment(id, time, content))
    )
  )
}
